package com.simon.hse.activity.education;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.CourseClassOutput;
import com.simon.hse.http.entity.OnlineStudyInput;
import com.simon.hse.http.entity.OnlineStudyOutput;
import com.simon.hse.interfaces.PopListener;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;


import retrofit2.Call;

/**
 * 在线学习
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_online_learning)
public class OnlineLearningActivity extends BaseActivity implements PopListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_online_learn_class)
    LinearLayout mLl_online_learn_class;

    @ViewInject(R.id.tv_online_learn_class)
    TextView mTv_online_learn_class;

    @ViewInject(R.id.et_online_learn_name)
    EditText mEt_online_learn_name;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;


    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<OnlineStudyOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();// 学习课程列表
    private List<CourseClassOutput.DataBean> mCourseClassList = new ArrayList<>();// 资料分类列表
    private String CourseClassId;// 类型ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("在线学习");

        initRecyclerView();
        initCourseClass();
        initData();
    }

    @Event(value = {R.id.iv_common_left, R.id.ll_online_learn_class})
    private void back(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.ll_online_learn_class:
                initCourseClassPop();
                break;
        }
    }

    private void initRecyclerView() {
        mEt_online_learn_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mDataBeanList.clear();
                initData();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage * 10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(OnlineLearningActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(OnlineLearningActivity.this, R.layout.layout_item_online_learning, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<OnlineStudyOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, OnlineStudyOutput.DataBean.PageDataBean dataBean) {
                TextView tv_online_study_title = holder.getView(R.id.tv_online_study_title);
                TextView tv_online_study_date = holder.getView(R.id.tv_online_study_date);
                TextView tv_online_study_classify = holder.getView(R.id.tv_online_study_classify);
                TextView tv_online_study_name = holder.getView(R.id.tv_online_study_name);

                tv_online_study_title.setText(dataBean.getCoursewareName());
                String createTime = dataBean.getCreateTime();
                String[] split = createTime.split(" ");
                tv_online_study_date.setText(split[0]);
                tv_online_study_classify.setText("资料分类：" + dataBean.getMark03());
                tv_online_study_name.setText(dataBean.getMark01());
            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                Intent intent = new Intent(OnlineLearningActivity.this, LearningContentActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("ID", mDataBeanList.get(position).getId());
                if (mDataBeanList.get(position).getMark02() != null){
                    bundle.putString("URL", mDataBeanList.get(position).getMark02().toString());
                }else{
                    bundle.putString("URL", "");
                }
                bundle.putBoolean("SHOW_TIME", false);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    private void initData() {
        OnlineStudyInput onlineStudyInput = new OnlineStudyInput();
        OnlineStudyInput.ModelBean modelBean = new OnlineStudyInput.ModelBean();

        if (!TextUtils.isEmpty(CourseClassId)) {
            modelBean.setCourseClassId(CourseClassId);
        }
        String trainName = mEt_online_learn_name.getText().toString();
        if (!TextUtils.isEmpty(trainName)) {
            modelBean.setCoursewareName(trainName);
        }

        onlineStudyInput.setModel(modelBean);
        onlineStudyInput.setLimit(10);
        onlineStudyInput.setOffset(10 * (currentPage - 1));

        Call<String> call = HttpManager.getInstance().requestService().ONLINE_STUDY_LIST(HttpManager.getInstance().requestBody(onlineStudyInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                OnlineStudyOutput onlineStudyOutput = new Gson().fromJson(result, OnlineStudyOutput.class);
                if (onlineStudyOutput.getResult().equals("Success")) {
                    totalPage = onlineStudyOutput.getData().getRowCount();
                    List<OnlineStudyOutput.DataBean.PageDataBean> dataBeanList = onlineStudyOutput.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(onlineStudyOutput.getMessage().toString());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 资料分类
     */
    private void initCourseClass() {
        Call<String> call = HttpManager.getInstance().requestService().COURSE_CLASS();
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                CourseClassOutput courseClassOutput = new Gson().fromJson(result, CourseClassOutput.class);
                if (courseClassOutput.getResult().equals("Success")) {
                    List<CourseClassOutput.DataBean> dataBeanList = courseClassOutput.getData();
                    CourseClassOutput.DataBean dataBean = new CourseClassOutput.DataBean();
                    dataBean.setName("全部");
                    mCourseClassList.add(dataBean);
                    mCourseClassList.addAll(dataBeanList);
                } else {
                    ToastUtils.getInstance().showShortToastBottom(courseClassOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 资料分类-pop
     */
    private void initCourseClassPop() {
        View inflate = LayoutInflater.from(OnlineLearningActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(OnlineLearningActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(OnlineLearningActivity.this, R.layout.layout_item_common_more_department, mCourseClassList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<CourseClassOutput.DataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, CourseClassOutput.DataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                CourseClassOutput.DataBean dataBean = mCourseClassList.get(position);
                CourseClassId = dataBean.getId();
                mTv_online_learn_class.setText(dataBean.getName());

                mDataBeanList.clear();
                initData();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(OnlineLearningActivity.this, inflate, mLl_online_learn_class);
    }

    @Override
    public void upData() {
        currentPage = 1;
        mDataBeanList.clear();
        initData();
    }
}
